#include "connector.h"
#include "communication.h"
#include "clientmanagement.h"

#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

Connector::Connector()
{
}

void Connector::run()
{
    int server_sockfd, client_sockfd;
    int server_len, client_len;
    struct sockaddr_in server_addr;
    struct sockaddr_in client_addr;

    server_sockfd = socket(AF_INET, SOCK_STREAM, 0);

    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = 9015;
    server_len = sizeof(server_addr);
    bind(server_sockfd, (struct sockaddr*)&server_addr, server_len);

    listen(server_sockfd,5);
    signal(SIGCHLD, SIG_IGN);

    char buff[2048] = {'\0'};

    while(1)
    {
        client_len = sizeof(client_addr);
        client_sockfd = accept(server_sockfd, (struct sockaddr*)&client_addr, (socklen_t*)&client_len);

        read(client_sockfd, buff, 2048);
        qWarning("Read:");
        qWarning(buff);

        cout << "dsd" <<endl << buff <<endl;

        Text t(QString::fromLocal8Bit(buff));
        memset(buff,'\0',sizeof(buff));

        cout << t.toString() << endl;

        QStringList rqst = t.toStringList();

        Text response;

        switch(t.getType())
        {
        case LOGIN_CODE:
            cout << "type: " << t.getType() << endl;
            response = ClientManagement::login(rqst.at(0), rqst.at(1));
            cout << "end" << rqst.at(0).toLocal8Bit().data() << "," << rqst.at(1).toLocal8Bit().data() << endl;
            break;
        case REG_CODE:
            break;
        case MOD_CODE:
            response = ClientManagement::modify(rqst.at(0),rqst.at(1),rqst.at(2));
            break;
        case QUERY_CODE:
            cout << "end" << rqst.at(0).toLocal8Bit().data() << "," << rqst.at(1).toLocal8Bit().data() << "," << rqst.at(2).toLocal8Bit().data() <<  endl;
            response = ClientManagement::query(rqst.at(0),rqst.at(1),rqst.at(2));
            break;
        case PURCHASE_CODE:
            response = ClientManagement::purchase(rqst.at(0),rqst.at(1),rqst.at(2));
            break;
        case HISTTORY_CODE:
            response = ClientManagement::queryHistory(rqst.at(0));
            break;
        case CANCELL_CODE:
            response = ClientManagement::cancell(rqst.at(0));
            break;
        }

        write(client_sockfd, response.toString(), response.length());
        qWarning("Write:");
        qWarning(response.toString());

        close(client_sockfd);
    }
}
